import React from 'react';
import {IMAGE_HOST_TEST, IMAGE_HOST_PROD, LOGIN_PATH} from 'src/constants'
import {push} from 'react-router-redux';
import img2 from '../img/2.jpg';
import {Card, Col, Badge, List} from 'amazeui-touch';
import {Link} from 'react-router'
import ModalExample from '../components/ModalExample';
import Loading from '../components/Loading'

export function authRouteResolver(store) {
    return (nextState, replace) => {
        const {auth} = store.getState();
        const {pathname} = nextState.location;
        if (auth.RET_CODE === "error" && `${pathname}` !== LOGIN_PATH) {
            store.dispatch(push(LOGIN_PATH));
        }
    }
}

export function goods(data) {
    const header = (
        <Card.Child cover={img2}>
            <h3 className="card-title">
                五折起
            </h3>
        </Card.Child>
    );
    let menus = [];
    if (data.RET_CODE === "error") {
        menus.push(<Loading/>);
    } else {
        data.goodsList.forEach((item, index) => {
            menus.push(<Card header={header} footer={
         <Card.Child role="footer">
            <Link to={{pathname: `/GoodDetail`, query: {goodId: item.id}}}>购买</Link>
            <Link>
                <ModalExample
                    title="推荐给好友"
                    modalProps={{role: 'actions'}}
                    method={"a"}
                >
                    <div className="modal-actions-group">
                        <List>
                            <List.Item className="modal-actions-header">分享到</List.Item>
                            <List.Item>微信</List.Item>
                            <List.Item className="modal-actions-alert">
                                Twitter</List.Item>
                        </List>
                    </div>
                </ModalExample>
            </Link>
            <a href="javascript: void(0)">详情</a>
        </Card.Child>
        }
                             key={index}>{item.name}{item.price}{item.oldPrice}<br />
                {item.detail}<br/>
            </Card>);
        });
    }
    return menus;
}

export function kind(data) {
    let list = [];
    if (data.RET_CODE === "error") {
        list.push(<Loading/>);
    } else {
        data.menuList.forEach((item, index) => {
            const imgSrc = "http://10.0.1.24:8080/pic/bing1.jpg";
            list.push(<Col key={index}> <Link to={{pathname: `/Goods`, query: {menuId: item.id}}}><img
                src={imgSrc}/>
                <div>{item.name}</div>
            </Link></Col>);
        });
    }
    return list;
}

export function kindList(data) {
    let list = [];
    data.forEach((item, index) => {
        list.push(
            <List.Item
                icon={'bars'}
                key={index}
                linkComponent={Link}
                linkProps={{to: `/Goods`,query: {menuId: item.id}}}
                title={item.name}
            >
            </List.Item>
        );
    });
    return list;
}
export function totalPrice(data) {
    let price = 0;
    data.map((item) => {
        price += item.price;
    });
    return price;
}

export function cartNum(data) {
    let num = 0;
    data.map(() => {
        num++;
    });
    return num;
}

export function status(orderStatus, payStatus) {
    let list = [];
    if (orderStatus === "1" && payStatus === "1") {
        list.push(<div><Badge rounded amStyle="success">已发货</Badge>&nbsp;&nbsp;<Badge rounded
                                                                                      amStyle="success">已支付</Badge>
        </div>);
    }
    else if (orderStatus === "1" && payStatus === "0") {
        list.push(<div><Badge rounded amStyle="success">已发货</Badge>&nbsp;&nbsp;<Badge rounded
                                                                                      amStyle="alert">未支付</Badge>
        </div>);
    } else if (orderStatus === "0" && payStatus === "1") {
        list.push(<div><Badge rounded amStyle="warning">未发货</Badge>&nbsp;&nbsp;<Badge rounded
                                                                                      amStyle="success">已支付</Badge>
        </div>);
    }
    else if (orderStatus === "0" && payStatus === "0") {
        list.push(<div><Badge rounded amStyle="warning">未发货</Badge>&nbsp;&nbsp;<Badge rounded
                                                                                      amStyle="alert">未支付</Badge>
        </div>);
    }
    return list;
}

export function toJson(data) {
    let list = [];
    data.map((item) => {
        let temp = {name: item.name, price: item.price, num: 1};
        list.push(temp);
    });
    return list;
}

export function createReducer(initialState, reducerMap) {
    return (state = initialState, action) => {
        const reducer = reducerMap[action.type];
        return reducer ? reducer(state, action.payload, action.params) : state
    }
}

const fixNumber = function (date) {
    const dateLength = 13;
    const len = date.length;

    let diffLen = dateLength - len;
    let diff = '';

    while (diffLen) {
        diff += '0';
        diffLen--;
    }

    return date + diff;
};

export function dateFormat(date, format) {
    let _format = format || 'yyyy-MM-dd';

    const d = date;
    const o = {
        'M+': d.getMonth() + 1, // month
        'd+': d.getDate(), // day
        'h+': d.getHours(), // hour
        'm+': d.getMinutes(), // minute
        's+': d.getSeconds(), // second
        'q+': Math.floor((d.getMonth() + 3) / 3), // quarter
        'S': d.getMilliseconds() // millisecond
    };

    if (/(y+)/.test(_format)) {
        _format = _format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
    }

    for (const k in o) {
        if (o.hasOwnProperty(k) && new RegExp('(' + k + ')').test(_format)) {
            _format = _format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
    }

    return _format;
}

export function imgTrustUrl(url) {
    if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
        return IMAGE_HOST_TEST + url
    } else if (process.env.NODE_ENV === 'production') {
        return IMAGE_HOST_PROD + url
    } else {
        return url
    }
}

export function isPromise(value) {
    if (value !== null && typeof value === 'object') {
        return value.promise && typeof value.promise.then === 'function'
    }
}

//向购物车中添加商品
export function addProduct(product) {
    let ShoppingCart = localStorage.getItem("ShoppingCart");
    if (ShoppingCart === null || ShoppingCart === "") {
        //第一次加入商品
        localStorage.setItem("ShoppingCart", JSON.stringify(product));
    } else {
        let jsonStr = JSON.parse(ShoppingCart);
        let productList = jsonStr.showGoodsMsg;
        let result = false;
        //查找购物车中是否有该商品
        for (const i in productList) {
            if (productList[i].id === product.showGoodsMsg[0].id) {
                result = true;
                console.log("here");
            }
        }
        if (!result) {
            //没有该商品就直接加进去
            productList.push(product.showGoodsMsg[0]);
        }
        localStorage.setItem("ShoppingCart", JSON.stringify(jsonStr));
    }
}

//删除购物车商品
export function deleteProduct(productId) {
    let ShoppingCart = localStorage.getItem("ShoppingCart");
    let jsonStr = JSON.parse(ShoppingCart);
    let productList = jsonStr.showGoodsMsg;
    let list = [];
    for (const i in productList) {
        if (productList[i].id === productId) {
            console.log("删除商品！");
        } else {
            list.push(productList[i]);
        }
    }
    jsonStr.showGoodsMsg = list;
    localStorage.setItem("ShoppingCart", JSON.stringify(jsonStr));
}